package cn.yunhe.dao.impl;

import cn.yunhe.dao.ITopicDao;
import cn.yunhe.entity.Topic;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import java.sql.SQLException;
import java.util.List;

public class TopicDao extends HibernateDaoSupport implements ITopicDao {

    @Override
    public List<Topic> search(final Topic topic) {
        List<Topic> list = getHibernateTemplate().executeFind(
                new HibernateCallback() {
                    @Override
                    public Object doInHibernate(Session session) throws HibernateException, SQLException {
                        Criteria cri = session.createCriteria(Topic.class);
                        if (topic != null) {
                            if (topic.getTitle() != null && topic.getTitle().trim().length() > 0) {
                                cri.add(Restrictions.like("title", topic.getTitle(), MatchMode.ANYWHERE));
                            }
                        }
                        return cri.list();
                    }
                }
        );
        return list;
    }

    @Override
    public List<Topic> searchByArgs(String hql) {
        return super.getHibernateTemplate().find(hql);
    }


    @Override
    public void add(Topic topic) {
        super.getHibernateTemplate().save(topic);
    }

    @Override
    public void del(int tid) {
        super.getHibernateTemplate().delete(get(tid));
    }

    public Topic get(int tid) {
        return getHibernateTemplate().get(Topic.class, tid);
    }

    @Override
    public void up(Topic topic) {
        super.getHibernateTemplate().update(topic);
    }
}
